package com.lincoln.bean;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Api通用继承,也可作为工具类使用
 *
 * @author lincoln
 */
public class BaseApi {
    public static ServletRequestAttributes getServletRequestAttributes() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes;
    }

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        return getServletRequestAttributes().getRequest();
    }

    /**
     * 获取response
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        return getServletRequestAttributes().getResponse();
    }

    private ThreadLocal<String> body = new ThreadLocal<>();

    /**
     * 获取当前请求的请求体
     *
     * @return
     */
    public String getBody() {
        if (body.get() == null) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(getRequest().getInputStream()));
                body.set(reader.toString());
                return body.get();
            } catch (Exception e) {
                return "";
            }
        } else {
            return body.get();
        }
    }

    /**
     * 移除body
     */
    public void unloadBody() {
        if (body.get() != null) {
            body.remove();
        }
    }

    /**
     * 将当前请求体转化为json
     *
     * @return
     */
    public JSONObject getBodyJson() {
        try {
            return JSONObject.parseObject(getBody());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 从请求体中取出参数
     *
     * @return
     */
    public <T> T getBodyParams(String paramName) {
        try {
            return (T) getBodyJson().get(paramName);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 从请求体中取出参数
     *
     * @return
     */
    public JSONObject getBodyParamsJsonObject(String paramName) {
        try {
            return getBodyJson().getJSONObject(paramName);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 为multipart/form-data类型的请求体切割参数
     *
     * @return
     */
    public static Map<String, List<String>> cutFormDataBody(String body) {
        if (body == null || "".equals(body)) {
            return new HashMap<>(0);
        }
        String[] strs = body.split("Content-Disposition: form-data; name=\"");
        Map<String, List<String>> result = new HashMap<>(10);
        if (strs == null || strs.length <= 0) {
            return new HashMap<>(0);
        }
        for (String str : strs) {
            try {
                String key = str.substring(0, str.indexOf("\"\r\n\r\n"));
                str = str.substring(key.length() + "\"\r\n\r\n".length());
                String value = str.substring(0, str.indexOf("\r\n"));
                List<String> v = new LinkedList<>();
                v.add(value);
                result.put(key, v);
            } catch (Exception e) {
                continue;
            }
        }
        return result;
    }
}
